//
//  AddLinkmanController.swift
//  ShareCar
//
//  Created by jiuzhongkeji on 2018/11/26.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit
import Contacts
import ContactsUI

class AddLinkmanController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    var titles = [(image:"personLinkman",title:"关系",detail:"请选择"),
                  (image:"addLinkManNumber",title:"联系方式",detail:"通讯录")]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    //TODO: - IBAction
    
    @IBAction func commitLinkman(_ sender: UIButton) {
        
    }
}

extension AddLinkmanController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titles.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = titles[indexPath.row].title
        cell.detailTextLabel?.text = titles[indexPath.row].detail
        cell.imageView?.image = UIImage(named: titles[indexPath.row].image)
        return cell
    }
}

extension AddLinkmanController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        switch indexPath.row {
        case 0:
            actionSheetchooseLinkman { i in
                let cell = tableView.cellForRow(at: indexPath)
                cell?.detailTextLabel?.text = i
                cell?.detailTextLabel?.textColor = UIColor(hexString: "6c6c8d")
            }
        case 1:
            let picker = CNContactPickerViewController()
            picker.delegate = self
            present(picker, animated: true)
        default:
            break
        }
    }
}

extension AddLinkmanController: CNContactPickerDelegate {
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        if let phone = contact.phoneNumbers.first {
            let indexPath = IndexPath(row: 1, section: 0)
            let cell = tableView.cellForRow(at: indexPath)
            cell?.detailTextLabel?.text = phone.value.stringValue
            cell?.detailTextLabel?.textColor = UIColor(hexString: "6c6c8d")
        }
    }
}
